﻿#include "login.h"
#include "eventtype.h"
#include "NetWork.h"
#include <QDebug>
#include "neteventdispatch.h"
#include "debug.h"
#include "IM.pb.h"
#include "netdef.h"
#include "accountdata.h"

Login::Login(QWidget *parent)
	: FramelessWidget(parent)
{
	ui.setupUi(this);
	FramelessWidget::setBarHeight(150);
//	m_server_connect = new NetServerConnect(this);
	//m_server_connect->moveToThread(m_server_connect);

	connect(ui.close, &QPushButton::clicked, this, [&]() {this->close(); });
	connect(ui.login, &QPushButton::clicked, this, &Login::login);

	//connect(m_server_connect,& NetServerConnect::errConnectServer, this, [&]() {qDebug() << "     ]]]]]]  connetc err  " << endl; },Qt::ConnectionType::QueuedConnection);


//	m_server_connect->connectServer("192.168.12.100", 1223);
	m_net_dispatch = NetEventDispatch::getInstance();
	m_net_dispatch->startDispatch();
	m_net_dispatch->startNetWork();
	m_net_dispatch->registerEvent(UEvent::connectFailEvent, this);
	m_net_dispatch->registerEvent(UEvent::loginEvent, this);

	m_net_dispatch->registerEvent(UEvent::getFriendListEvent, AcountDataBuffer::getInstance());

	connect(AcountDataBuffer::getInstance(), &AcountDataBuffer::dataRead, this, [&]() {
		this->accept();
	});
}

void Login::login()
{
	QString u = ui.ac->text();
	QString psw = ui.pswd->text();

	m_ac_muber = u;

	IM_Protocol::LoginRequest r;
	r.set_ac(u.toStdString().c_str());
	r.set_paw(psw.toStdString().c_str());
	char buf[1024];
	r.SerializeToArray(buf, r.ByteSize());
	m_net_dispatch->getTcpNetWorkInstance()->sendData(PktType_Login_request,buf,r.ByteSize());
}

bool Login::event(QEvent * event)
{
	auto type = event->type();

	if (type==UEvent::connectFailEvent)
	{
		Debug("链接服务器失败\n");
	}
	else if(type==UEvent::loginEvent)
	{
		LoginEvent * e = (LoginEvent *)event;
		switch (e->result)
		{
			case LoginRsultCode_sucess:
			{
				Debug("登陆成功!\n token:%s", e->token.toStdString().c_str());

				IM_Protocol::FriendListRequest r;
				r.set_ac_id(m_ac_muber.toStdString());
				r.set_token(e->token.toStdString());

				char buf[1024];
				r.SerializeToArray(buf, r.ByteSize());
				m_net_dispatch->getTcpNetWorkInstance()->sendData(PktType_GetFriend_Request, buf, r.ByteSize());

				/////////////////////////////////////////


			}
			break;
			case LoginRsultCode_None:
				Debug("登陆失败！  密码错误或者不从在 \n");
				break;
			case LoginRsultCode_Repetition:
				Debug("禁止重复登陆\n");
				break;
			default:
				Debug("未知错误\n");
				break;
		}
	}

	return QWidget::event(event);
}
